/************************************************************************
Copyright 2003, 2004, 2005, 2006, 2007, 2008 Grid Technology Research Center,
National Institute of Advanced Industrial Science and Technology.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
************************************************************************/

package jp.aist.gtrc.plus.scheduler.job;

import java.util.Collection;

import jp.aist.gtrc.plus.scheduler.SchedulerOptions;
import jp.aist.gtrc.plus.scheduler.specific.pbs.util.PBSErrorCode;
import jp.aist.gtrc.plus.scheduler.specific.pbs.util.PBSException;
import jp.aist.gtrc.plus.scheduler.status.JobStatus;
import jp.aist.gtrc.plus.scheduler.sys.SchedulerException;
import jp.aist.gtrc.plus.scheduler.util.TextUtil;

import org.apache.log4j.Logger;

public abstract class Scheduler {

	protected static final Logger logger = Logger.getLogger(Scheduler.class);

	public abstract void init(SchedulerOptions options) throws SchedulerException;
	public abstract JobStatus selectJob(Collection<JobStatus> jobs);

	public static Scheduler getScheduler(SchedulerOptions options) throws SchedulerException {

                String target = options.getTargetSystem();
		String algo = options.getSchedAlgolithm();
		logger.info("Try to use " + algo + " scheduler for " + target);
		if (TextUtil.isEmpty(algo)) {
			throw new PBSException(PBSErrorCode.RMNOPARAM);
		}

		Scheduler sched;

                if (target.equalsIgnoreCase("pbsdyn")) {
                    /* Plus's job scheduler is set to dummy since 
		     * dynamic provisioning has its own job scheduler
		     */
		    sched = new DummyScheduler(); 
                } else {
		    if (algo.equalsIgnoreCase("Fifo")){
			sched = new FifoScheduler();
      		    } else if (algo.equalsIgnoreCase("Sort")) {
			sched = new SortScheduler();
		    } else if (algo.equalsIgnoreCase("Edf")) {
			sched = new EdfScheduler();
		    } else {
			try {
				// 'algo' must be full class name:
				// (ex: "jp.aist.gtrc.plus.scheduler.job.Foo")
				Class<?> c = Class.forName(algo);
				sched = (Scheduler)c.newInstance();
			} catch (Exception e) {
				logger.debug("Load failed", e);
				throw new SchedulerException("Load failed: " + algo);
			}
		    }
                }

		assert(sched != null);
		sched.init(options);

		return sched;

	}

}
